<template>
  <div class="y-config-table wh-full">
    <a-table
      :rowKey="rowKey"
      class="wh-full mb-10px"
      :style="tableHeight"
      :dataSource="tableData"
      :columns="innerColumns"
      :pagination="false"
    >
    </a-table>
    <div class="flex justify-center" v-if="page">
      <a-pagination
        v-model:current="pagination.pageNum"
        v-model:pageSize="pagination.limit"
        :total="pagination.total"
        @change="handlePagination"
      />
    </div>
  </div>
</template>
<script setup>
import { computed, onMounted, reactive } from 'vue';
import { useColumns } from './hooks/useColumns';
import { buildTree } from "@/utils/buildTree";
defineOptions({
  name: 'YConfigTable',
});
const props = defineProps({
  columns: {
    type: Array,
    default: () => [],
  },
  dataRequest: {
    type: Function,
    default: () => ({}),
  },
  requestParams: {
    type: Object,
    default: null,
  },
  page: {
    type: [Object, Boolean],
    default: false,
  },
  rowKey:{
    type: String,
    default: 'id'
  },
  tree:{
    type: Boolean,
    default: false
  }
});

watch(
  () => props.requestParams,
  async (newVal, oldVal) => {
    await getList();
  },
  {
    deep: true,
  }
);
const { columns } = props;
const innerColumns = useColumns(columns);
const tableHeight = computed(()=>{
  return `height:calc(100% - ${props.page ? 42 : 0}px)`

})
const tableData = ref([]);
const pagination = reactive({
  pageNum: 1, //当前页码
  limit: 10, //每页条数
  pageSizeOptions: [10, 20, 30, 40, 50], //每页条数选项
  defaultPageSize: 20, //默认每页条数
  total: 0, //总记录数
  hideOnSinglePage: true, //只有一页时是否隐藏分页器
  ...(props.page ? props.page : {}),
});
const treeFields = {
  rowField:"id",
  parentField: 'parentId',
    childrenField: 'children',
    ...(!!props.tree ? props.tree : {})
}
const getList = async () => {
  const page = props.page
    ? {
        pageNum: pagination.pageNum,
        limit: pagination.limit,
      }
      : undefined;
      const res = await props.dataRequest(props.requestParams, page);

  if (res) {
    if (props.page) {
      if(props.tree){
        tableData.value = buildTree(res.data,treeFields);
      }else{
        tableData.value = res.data;
      }
      pagination.total = res.total;
    } else {
      if(props.tree){
        tableData.value = buildTree(res,treeFields);
      }else{

        tableData.value = res;
      }
    }
  }
};

const handlePagination = async () => {
  await getList();
};

const refresh = async () => {
  await getList();
}

// 暴露给使用者
defineExpose({
  refresh
})


onMounted(async () => {
  await getList();
});
</script>
